package com.gitee.tanmingjian.httptunnel.core.util;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class DataPackageUtils {

    public static byte[] getLongBinary(int num) {
        byte[] result = new byte[4];
        result[0] = (byte) ((num >> 24) & 0xFF);
        result[1] = (byte) ((num >> 16) & 0xFF);
        result[2] = (byte) ((num >> 8) & 0xFF);
        result[3] = (byte) (num & 0xFF);
        return result;
    }

    public static int getLong(ByteBuffer byteBuffer) {
        byte[] binary = new byte[4];
        byteBuffer.get(binary);
        int result = 0;
        result += Byte.toUnsignedInt(binary[0]) << 24;
        result += Byte.toUnsignedInt(binary[1]) << 16;
        result += Byte.toUnsignedInt(binary[2]) << 8;
        result += Byte.toUnsignedInt(binary[3]);
        return result;
    }

    public static byte[] getShortBinary(int num) {
        byte[] result = new byte[2];
        result[0] = (byte) ((num >> 8) & 0xFF);
        result[1] = (byte) (num & 0xFF);
        return result;
    }

    public static int getShort(ByteBuffer byteBuffer) {
        byte[] binary = new byte[2];
        byteBuffer.get(binary);
        int result = 0;
        result += Byte.toUnsignedInt(binary[0]) << 8;
        result += Byte.toUnsignedInt(binary[1]);
        return result;
    }

    public static byte[] getDummy(int count) {
        return new byte[count];
    }

    public static void getDummy(ByteBuffer byteBuffer, int count) {
        byte[] bytes = new byte[count];
        byteBuffer.get(bytes);
    }

    public static byte[] getBlock(String val) {
        if (val == null) {
            return new byte[]{(byte) 0xFF};
        }
        byte[] bytes = val.getBytes(StandardCharsets.UTF_8);
        int length = bytes.length;
        byte[] result;
        if (length < 0xFE) {
            result = new byte[length + 1];
            result[0] = (byte) length;
            System.arraycopy(bytes, 0, result, 1, bytes.length);
        } else {
            result = new byte[length + 5];
            result[0] = (byte) 0xFE;
            System.arraycopy(getLongBinary(length), 0, result, 1, 4);

            System.arraycopy(bytes, 0, result, 5, bytes.length);
        }
        return result;
    }

    public static String getBlockString(ByteBuffer byteBuffer) {
        byte lengthByte = byteBuffer.get();
        if (lengthByte == (byte) 0xFF) {
            return null;
        }
        int length;
        if (lengthByte == (byte) 0xFE) {
            length = getLong(byteBuffer);
        } else {
            length = Byte.toUnsignedInt(lengthByte);
        }
        byte[] strBytes = new byte[length];
        byteBuffer.get(strBytes);
        return new String(strBytes, StandardCharsets.UTF_8);
    }

}
